﻿#include "test1.h"
BTNode* BuyBTNode(char val) // 创建一个节点
{
	BTNode* newnode = (BTNode*)malloc(sizeof(BTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->data = val;
	newnode->left = NULL;
	newnode->right = NULL;
	return newnode;
}

BTNode* BinaryTreeCreate() // 通过前序遍历的数组"ABD##E#H##CF##G##"构建二叉树
{
	BTNode* n1 = BuyBTNode('A');
	BTNode* n2 = BuyBTNode('B');
	BTNode* n3 = BuyBTNode('C');
	BTNode* n4 = BuyBTNode('D');
	BTNode* n5 = BuyBTNode('E');
	BTNode* n6 = BuyBTNode('F');
	BTNode* n7 = BuyBTNode('G');
	BTNode* n8 = BuyBTNode('H');

	n1->left = n2;
	n1->right = n3;
	n2->left = n4;
	n2->right = n5;
	n3->left = n6;
	n3->right = n7;
	n5->right = n8;
	return n1;
}

void BinaryTreeDestory(BTNode** root) // 二叉树销毁
{
	if (*root == NULL)
	{
		return;
	}
	BinaryTreeDestory(&((*root)->left));
	BinaryTreeDestory(&((*root)->right));
	free(*root);
	*root = NULL;
}

void BinaryTreePrevOrder(BTNode* root) // 二叉树前序遍历 
{
	if (root == NULL)
	{
		printf("#");
		return;
	}
	printf("%c", root->data);
	BinaryTreePrevOrder(root->left);
	BinaryTreePrevOrder(root->right);
}

void BinaryTreeInOrder(BTNode* root) // 二叉树中序遍历
{
	if (root == NULL)
	{
		printf("#");
		return;
	}
	BinaryTreePrevOrder(root->left);
	printf("%c", root->data);
	BinaryTreePrevOrder(root->right);
}

void BinaryTreePostOrder(BTNode* root) // 二叉树后序遍历
{
	if (root == NULL)
	{
		printf("#");
		return;
	}
	BinaryTreePrevOrder(root->left);
	BinaryTreePrevOrder(root->right);
	printf("%c", root->data);
}

int BinaryTreeSize(BTNode* root) // 二叉树节点个数
{
	if (root == NULL)
	{
		return 0;
	}

	return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}

int BinaryTreeLeafSize(BTNode* root) // 二叉树叶子节点个数
{
	if (root == NULL)
	{
		return 0;
	}
	if (root->left == root->right && root->left == NULL)
	{
		return 1;
	}

	return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
}

int BinaryTreeLevelKSize(BTNode* root, int k) // 二叉树第k层节点个数
{
	if (root == NULL)
	{
		return 0;
	}
	if (k == 1)
	{
		return 1;
	}

	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}

int BinaryTreeDepth(BTNode* root) //⼆叉树的深度/⾼度
{
	if (root == NULL)
	{
		return 0;
	}
	int leftDep = BinaryTreeDepth(root->left);
	int rightDep = BinaryTreeDepth(root->right);
	return 1 + (leftDep > rightDep ? leftDep : rightDep);
}

BTNode* BinaryTreeFind(BTNode* root, BTDataType x) // 二叉树查找值为x的节点
{
	if (root == NULL)
	{
		return NULL;
	}
	if (root->data == x)
	{
		return root;
	}
	BTNode* left = BinaryTreeFind(root->left, x);
	if (left)
		return left;
	BTNode* right = BinaryTreeFind(root->right, x);
	if (right)
		return right;
	return NULL;
}

